﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace Technoera.Common.Interop.OleDb
{
    internal class ReflectionHelper
    {
        public static object GetNestedPropertyValue(Type parentType, string propertyFullName, object instance)
        {
            if (propertyFullName.IndexOf('.') > -1)
            {
                string thisLevelPropertyName = propertyFullName.Split(new char[] { '.' })[0];
                PropertyInfo thisLevelProperty = parentType.GetProperty(thisLevelPropertyName);
                if (thisLevelProperty == null) throw new TargetException(string.Format("Unable to find property '{0}' in Type '{1}'.", propertyFullName, parentType.FullName));
                object thisLevelInstance = thisLevelProperty.GetValue(instance, null);

                string childPropertyName = propertyFullName.Substring(thisLevelPropertyName.Length + 1);
                return GetNestedPropertyValue(thisLevelProperty.PropertyType, childPropertyName, thisLevelInstance);
            }
            else
            {
                PropertyInfo property = parentType.GetProperty(propertyFullName);
                if (property == null) throw new TargetException(string.Format("Unable to find property '{0}' in Type '{1}'.", propertyFullName, parentType.FullName));
                return property.GetValue(instance, null);
            }
        }
    }
}
